import java.util.ArrayList;
import java.util.List;

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
        next = null;
    }
}

/**
 * https://leetcode-cn.com/problems/linked-list-cycle-ii/
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode root = head;
        List<ListNode> list = new ArrayList<>();
        while (root != null) {
            if (list.contains(root))
                break;
            list.add(root);
            root = root.next;
        }
        return root;
    }

    public ListNode detectCycle2(ListNode head) {
        if (head == null || head.next == null)
            return null;
        ListNode fast = head, slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow)
                break;
        }
        if (fast != slow)
            return null;
        slow = head;
        while (fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }
}